package cn.kilo.infrastructure.persistent.support;

import cn.kilo.domain.model.order.vo.OrderStatusVO;
import cn.kilo.infrastructure.persistent.redis.RedissonService;
import cn.kilo.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author kilok
 * 订单接取服务,通过redis分布式锁保证一个订单只能由一个骑手接取
 */
@Slf4j
@Component
public class TakeOrder {

    @Resource
    @Qualifier("redissonService")
    private RedissonService redisService;

    public Boolean takeOrder(Long orderId,String ridgepole) {
        String lock = Constants.RedisKey.LOCK_KEY + Constants.UNDERLINE + orderId;
        String cacheKey=Constants.RedisKey.ORDER_INFO+Constants.UNDERLINE+orderId;
        try {
            //30
            boolean locked = redisService.setNx(lock+"_tryLock");
            if (locked) {
                log.info("锁获设置成功");
                OrderStatusVO order = redisService.getValue(cacheKey);
                log.info("order:{}",order);

                String key = Constants.RedisKey.SORTEDSET_DEPARTMENT + Constants.UNDERLINE + ridgepole;
                log.info("删除:{}中的订单:{}",key,order);
                redisService.deleteSortedSet(order, key);
                return true;
            } else {
                log.info("锁获取失败");
                return false;
            }
        } catch (Exception e) {
            log.info("",e);
        }
        return false;
    }
}
